//
//  SetViewController.m
//  ExploreWorld
//
//  Created by dlios on 15/7/13.
//  Copyright (c) 2015年 chenlin. All rights reserved.
//

#import "SetViewController.h"
#import "AppDelegate.h"
#import "Header.h"
#import "SetCell.h"
#import "AboutUsController.h"
#import "SevenSwitch.h"
#import "MyTabBar.h"
#import "SevenSwitch.h"
#import "LogInNavi.h"
#import "AniView.h"


#import "DataBaseManager.h"
#import "CollectModel.h"

#import "DBViewController.h"
#import "SDImageCache.h"


@interface SetViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) AniView *leftView;
@property (nonatomic, retain) SevenSwitch *mySwitch;
@property (nonatomic, retain) AniView *subView;
@property (nonatomic, retain) UIButton *leftButton;
@property (nonatomic, retain) UIButton *buttonTX;
@property (nonatomic, retain) UIButton *buttonTXWB;
@property (nonatomic, retain) UIButton *buttonXL;
@property (nonatomic, assign) NSInteger count;

@end

@implementation SetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
<<<<<<< HEAD
=======
    // 暂无用
    {
//    
//    self.count = 1;
//    self.leftButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 30, 30)];
//    
//    [self.leftButton setImage:[UIImage imageNamed:@"iconfont-fangbianlogin1"] forState:UIControlStateNormal];
//    [self.leftButton addTarget:self action:@selector(insertMe:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:self.leftButton];
//    self.navigationItem.leftBarButtonItem = leftItem;
    }
    
>>>>>>> 5aabf5f3ed3bf002994c076f8caa1ea0a394d1cf
    
    self.title = @"设置";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, [UIFont fontWithName:@"Helvetica-Bold" size:20], NSFontAttributeName, nil]];
    
<<<<<<< HEAD
    UIImageView *viewBackground = [[UIImageView alloc] initWithFrame:CGRectMake(-10, 64, WIDTH + 20, 200)];
    
    viewBackground.image = [UIImage imageNamed:@"D12570B90832D20F4939A76232ACA683.jpg"];
=======
    UIImageView *viewBackground = [[UIImageView alloc] initWithFrame:CGRectMake(-10, 64, WIDTH + 20, 200 + 10)];

    viewBackground.image = [UIImage imageNamed:@"D12570B90832D20F4939A76232ACA683"];
>>>>>>> 5aabf5f3ed3bf002994c076f8caa1ea0a394d1cf
    [self.view addSubview:viewBackground];
    [viewBackground release];
    
    
    // CABaseAnimation 基础动画
    CABasicAnimation *animation1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    animation1.fromValue = [NSNumber numberWithInt:1];
    animation1.toValue = [NSNumber numberWithFloat:1.2];
    animation1.duration = 5.0f;
    animation1.autoreverses = YES;
    animation1.repeatCount = NSIntegerMax;
    [viewBackground.layer addAnimation:animation1 forKey:@"suibian"];
    
    
    UIView *viewForImage = [[UIView alloc] initWithFrame:CGRectMake(WIDTH / 2 - 40, viewBackground.frame.size.height / 1.8, 80, 80)];
    viewForImage.layer.cornerRadius = 40;
    viewForImage.layer.borderColor = [UIColor whiteColor].CGColor;
    viewForImage.layer.borderWidth = 2;
    viewForImage.backgroundColor = [UIColor whiteColor];
    [viewForImage setClipsToBounds:YES];
    [self.view addSubview:viewForImage];
    [viewForImage release];
    
    UIButton *userHeadButton = [UIButton buttonWithType:UIButtonTypeCustom];
    userHeadButton.frame = viewForImage.bounds;
    [userHeadButton setImage:[UIImage imageNamed:@"userTouXiang.jpg"] forState:UIControlStateNormal];
    userHeadButton.layer.cornerRadius = 35;
    [userHeadButton clipsToBounds];
    [viewForImage addSubview:userHeadButton];
    [userHeadButton addTarget:self action:@selector(tabAction) forControlEvents:UIControlEventTouchUpInside];
    
    
<<<<<<< HEAD
    self.UserLogInLabel = [[UILabel alloc] init];
    self.UserLogInLabel.frame = CGRectMake(WIDTH / 2 - 40, viewForImage.frame.size.width + viewForImage.frame.origin.y + 5, 100, 20);
    self.UserLogInLabel.text = @"用户未登录";
    self.UserLogInLabel.center = CGPointMake(WIDTH / 2, (viewBackground.frame.size.height + 200)  / 2);
    self.UserLogInLabel.textAlignment = NSTextAlignmentCenter;
    self.UserLogInLabel.textColor = [UIColor whiteColor];
    self.UserLogInLabel.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:self.UserLogInLabel];
    [self.UserLogInLabel release];
=======
    UILabel *UserLogInLabel = [[UILabel alloc] init];
    UserLogInLabel.frame = CGRectMake(WIDTH / 2 - 45, viewForImage.frame.size.width + viewForImage.frame.origin.y, 80, 20);
    UserLogInLabel.text = @"用户未登录";
    UserLogInLabel.textColor = [UIColor whiteColor];
    UserLogInLabel.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:UserLogInLabel];
    [UserLogInLabel release];
    
    UIImageView *coin = [[UIImageView alloc] init];
    coin.frame = CGRectMake(WIDTH / 2 + UserLogInLabel.frame.size.width / 2 - 3,viewForImage.frame.size.width + viewForImage.frame.origin.y + 2, 15, 15);
    coin.image = [UIImage imageNamed:@"seller-4-1"];
    [self.view addSubview:coin];
    [coin release];
>>>>>>> 5aabf5f3ed3bf002994c076f8caa1ea0a394d1cf
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, viewBackground.frame.origin.y + viewBackground.frame.size.height, WIDTH, HEIGHT - viewBackground.frame.origin.y - viewBackground.frame.size.height - 50) style:UITableViewStylePlain];
    self.tableView.tag = 1000;
    self.tableView.scrollEnabled = YES;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
//  [self creatView];
    self.tabBarController.tabBar.hidden = NO;
    
}

- (void)viewWillAppear:(BOOL)animated
{
//    self.leftView.frame = CGRectMake(-WIDTH, 0, WIDTH, HEIGHT);
//    self.count = 0;
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
    
}




// 暂无用
- (void)insertMe:(UIButton *)button
{
    UILabel *UserLogIn = [[UILabel alloc] initWithFrame:CGRectMake(20, HEIGHT / 6, 80, 30)];
    UserLogIn.text = @"用户登录";
    UserLogIn.textColor = [UIColor whiteColor];
    [self.subView addSubview:UserLogIn];
    [UserLogIn release];
    
    
    if (1 == self.count) {
        [UIView animateWithDuration:0.5 delay:0.2 options:UIViewAnimationOptionLayoutSubviews animations:^{
            self.leftView.transform = CGAffineTransformMakeTranslation(WIDTH, 0);
            self.count++;
        } completion:^(BOOL finished) {
            
            self.buttonTX = [UIButton buttonWithType:UIButtonTypeCustom];
            [self.buttonTX setImage:[UIImage imageNamed:@"Tencent"] forState:UIControlStateNormal];
            self.buttonTX.frame = CGRectMake(20, HEIGHT / 6 + 50, 58, 58);
            [self.subView addSubview:self.buttonTX];
            
            self.buttonTXWB = [UIButton buttonWithType:UIButtonTypeCustom];
            self.buttonTXWB.frame = CGRectMake(22, HEIGHT / 6 + 150, 52, 52);
            [self.buttonTXWB setImage:[UIImage imageNamed:@"TencentWeiBo"] forState:UIControlStateNormal];
            [self.subView addSubview:self.buttonTXWB];
            
            self.buttonXL = [UIButton buttonWithType:UIButtonTypeCustom];
            self.buttonXL.frame = CGRectMake(24, HEIGHT / 6 + 250, 47, 47);
            [self.buttonXL setImage:[UIImage imageNamed:@"XinLangWeiBo"] forState:UIControlStateNormal];
            [self.subView addSubview:self.buttonXL];

#pragma 腾讯
{
            CABasicAnimation *animationTX = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
            // 什么状态开始放大
            // 从1倍比例开始
            animationTX.fromValue = [NSNumber numberWithInt:0];
            // 放大到什么状态结束
            // 放大到二倍结束
            animationTX.toValue = [NSNumber numberWithInt:1];
            // 动画执行时间
            animationTX.duration = 0.2f;
            // 把动画添加到layer
            [self.buttonTX.layer addAnimation:animationTX forKey:@"TX"];
}
            // iconfont-tengxunkongjian2 空间
            // iconfont-weibiaoti1 weiboXL
            // iconfont-tengxunweibo tenxunWB
            // 腾讯微博
#pragma 腾讯微博
{
        CABasicAnimation *animationTXWB = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        animationTXWB.fromValue = [NSNumber numberWithInt:0];
        animationTXWB.toValue = [NSNumber numberWithInt:1];
        animationTXWB.duration = 0.4f;
//        animationTXWB.beginTime = CACurrentMediaTime() + 0.5;
        [self.buttonTXWB.layer addAnimation:animationTXWB forKey:@"TXWB"];

}
            
#pragma 新浪微博
{
        CABasicAnimation *animationXLWB = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        animationXLWB.fromValue = [NSNumber numberWithInt:0];
        animationXLWB.toValue = [NSNumber numberWithInt:1];
        animationXLWB.duration = 0.6f;
//        animationXLWB.beginTime = CACurrentMediaTime() + 1;
        [self.buttonXL.layer addAnimation:animationXLWB forKey:@"XLWB"];

}
            self.count = 0;
        }];
    } else {
        NSLog(@"关");
 
        [UIView animateWithDuration:1 delay:0.2 options:UIViewAnimationOptionLayoutSubviews animations:^{
            self.leftView.transform = CGAffineTransformMakeTranslation(-WIDTH, 0);
            self.count = 1;
        } completion:^(BOOL finished) {
            [self.buttonXL removeFromSuperview];
            [self.buttonTXWB removeFromSuperview];
            [self.buttonTX removeFromSuperview];
        }];
    }
}

// 暂无用
- (void)tapAction
{
    [UIView animateWithDuration:0.5 delay:0.2 options:UIViewAnimationOptionLayoutSubviews animations:^{
        self.leftView.transform = CGAffineTransformMakeTranslation(-WIDTH, 0);
        self.count = 1;
    } completion:^(BOOL finished) {
        [self.buttonXL removeFromSuperview];
        [self.buttonTXWB removeFromSuperview];
        [self.buttonTX removeFromSuperview];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    } else {
        return 4;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString *Identifier = @"Identifier";
        SetCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
        if (cell == nil) {
            cell = [[SetCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];
        }
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        // cell.selectionStyle = UITableViewCellSelectionStyleNone;
        // cell.selected = NO;
        //cell的右边有一个小箭头，距离右边有十几像素；
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.label.font = [UIFont systemFontOfSize:20.0f];
        cell.backgroundColor = [UIColor clearColor];
        // cell.textLabel.textColor = [UIColor cyanColor];
        cell.label.font = [UIFont systemFontOfSize:17];
        // 点击颜色
        // cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        if (indexPath.row == 0) {
            cell.label.text = @"浏览历史";
            cell.image.image = [UIImage imageNamed:@"LLTakeoutFlowFirstEnabled.jpg"];
            cell.image.frame = CGRectMake(5, 8, 30, 30);
        } else if (indexPath.row == 1) {
            cell.label.text = @"我的收藏";
            cell.image.image = [UIImage imageNamed:@"feed_select_fav_icon"];
            cell.image.frame = CGRectMake(8, 10, 25, 25);
        }
        return cell;
    } else {
        static NSString *Identifier = @"Identifier";
        SetCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
        if (cell == nil) {
            cell = [[SetCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];
        }
        // cell.selectionStyle = UITableViewCellSelectionStyleNone;
        // cell的右边有一个小箭头，距离右边有十几像素；
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.label.font = [UIFont systemFontOfSize:20.0f];
        cell.backgroundColor = [UIColor clearColor];
        cell.label.font = [UIFont systemFontOfSize:17];
        // 点击颜色
        // cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        if (indexPath.row == 0) {
            cell.label.text = @"夜间模式";
            cell.image.image = [UIImage imageNamed:@"feed_select_my_footprint"];
            cell.image.frame = CGRectMake(8, 10, 25, 25);
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
<<<<<<< HEAD
            SevenSwitch *mySwitch2 = [[SevenSwitch alloc] initWithFrame:CGRectMake(WIDTH - 100, 10, 70, 25)];
=======
            SevenSwitch *mySwitch2 = [[SevenSwitch alloc] initWithFrame:CGRectMake(WIDTH - 75, 10, 60, 25)];
>>>>>>> 5aabf5f3ed3bf002994c076f8caa1ea0a394d1cf
            [mySwitch2 addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
            mySwitch2.offImage = [UIImage imageNamed:@"cross.png"];
            mySwitch2.onImage = [UIImage imageNamed:@"check.png"];
            mySwitch2.onColor = [UIColor colorWithHue:0.08f saturation:0.74f brightness:1.00f alpha:1.00f];
            mySwitch2.isRounded = NO;
            [cell.contentView addSubview:mySwitch2];
            [mySwitch2 setOn:YES animated:NO];
        } else if (indexPath.row == 1) {
            cell.label.text = @"清除缓存";
            cell.image.image = [UIImage imageNamed:@"14112022"];
            cell.image.frame = CGRectMake(8, 10, 25, 25);
            self.l = [[UILabel alloc]initWithFrame:CGRectMake(150, 10, 60, 25)];
        } else if (indexPath.row == 2) {
            cell.label.text = @"给个评分";
            cell.image.image = [UIImage imageNamed:@"rate_hao_ping_button"];
            cell.image.frame = CGRectMake(8, 10, 28, 28);
        } else {
            cell.label.text = @"版本信息";
            cell.image.image = [UIImage imageNamed:@"ac04a35953fea30f43ff8c0623f6b5fc.jpg"];
            cell.image.frame = CGRectMake(10, 8, 25, 25);
        }
        return cell;
    }
    
}

//计算单个文件大小
-(float)fileSizeAtPath{
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSLog(@"%lu",(unsigned long)array.count);
    NSString *path = [array firstObject];
    path = [NSString stringWithFormat:@"%@/Caches",path];
    
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size/1024.0/1024.0;
    }
    return 0;
}

//计算目录文件大小
//遍历文件夹获得文件夹大小，返回多少M
//- (float )folderSizeAtPath:(NSString*) folderPath{
//    NSFileManager* manager = [NSFileManager defaultManager];
//    if (![manager fileExistsAtPath:folderPath]) return 0;
//    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
//    NSString* fileName;
//    long long folderSize = 0;
//    while ((fileName = [childFilesEnumerator nextObject]) != nil){
//        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
//        folderSize += [self fileSizeAtPath:fileAbsolutePath];
//    }
//    return folderSize/(1024.0*1024.0);
//}



//清除文件
-(void)clearCache:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    [[SDImageCache sharedImageCache] cleanDisk];
}



- (void)nsl
{
    NSLog(@"asdasd");
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        DBViewController *d = [[DBViewController alloc]init];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            NSLog(@"浏览历史");
             d.str = @"浏览历史";
             [self.navigationController pushViewController:d animated:YES];
        }
        else if (indexPath.row == 1){
        NSLog(@"我的收藏");
        
            d.str =@"我的收藏";
             [self.navigationController pushViewController:d animated:YES];
         }
    }
    
    if (indexPath.section == 1) {
        if (indexPath.row == 1) {
            NSArray *array = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
             NSString *path = [array lastObject];
            path = [NSString stringWithFormat:@"%@/Caches",path];
            NSLog(@"%@",path);
         [self clearCache:path];
   
            NSLog(@"Library下Caches文件夹内容已清除");
        }
        
        if (indexPath.row == 2) {
            NSLog(@"给个评分");
            NSString *str = [NSString stringWithFormat:@"https://itunes.apple.com/cn/app/xing-kongfm/id1002256892?mt=8"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        }
        if (indexPath.row == 3) {
            AboutUsController *about = [[AboutUsController alloc] init];
            
            [self.navigationController pushViewController:about animated:YES];
        }
    }
}


// 给头部区域设置自定义视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    // 自定义视图的高度不由当前的试图对象决定
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = [UIColor grayColor];
    v.alpha = 0.15;
    return v;
}

// 控制头部高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
<<<<<<< HEAD
    if (section == 0) {
        return 0.045 * HEIGHT;
//    } else if (section == 1) {
//        return 0.07 * HEIGHT;
    } else {
        return 0;
    }
=======
    return 0.045 * HEIGHT;
>>>>>>> 5aabf5f3ed3bf002994c076f8caa1ea0a394d1cf
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return 0.045 * HEIGHT;
//}


- (void)tabAction
{
<<<<<<< HEAD
    [ShareSDK getUserInfoWithType:ShareTypeSinaWeibo
                      authOptions:nil
                           result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) {
                               if (result) {
                                   // 改变用户名
                                   self.UserLogInLabel.text = [userInfo nickname];
                                   // 改变头像
                                   [self.userHeadButton sd_setBackgroundImageWithURL:[NSURL URLWithString:[userInfo profileImage]] forState:UIControlStateNormal];
                                   
                                   NSLog(@"uid = %@",[userInfo uid]);
                                   NSLog(@"name = %@",[userInfo nickname]);
                                   NSLog(@"icon = %@",[userInfo profileImage]);
                                   //将信息保存到parse上
                                   PFQuery *query = [PFQuery queryWithClassName:@"UserInfo"];
                                   [query whereKey:@"uid" equalTo:[userInfo uid]];
                                   [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                                       
                                       if ([objects count] == 0)
                                       {
                                           PFObject *newUser = [PFObject objectWithClassName:@"UserInfo"];
                                           [newUser setObject:[userInfo uid] forKey:@"uid"];
                                           [newUser setObject:[userInfo nickname] forKey:@"name"];
                                           [newUser setObject:[userInfo profileImage] forKey:@"icon"];
                                           [newUser saveInBackground];
                                           
//                                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"欢迎注册" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles: nil];
//                                           [alertView show];
                                       }
                                       else
                                       {
//                                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"欢迎回来" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles: nil];
//                                           [alertView show];
                                       }
                                   }];
                                   
                                   //                                   LogInNavi *logIn = [[LogInNavi alloc] init];
                                   //                                   // 选择模态动画
                                   //                                   //                                   [self.navigationController pushViewController:logIn animated:YES];
                                   //                                   [logIn setModalPresentationStyle:UIModalPresentationFullScreen];
                                   //                                   [self presentViewController:logIn animated:YES completion:^{
                                   //                                       //
                                   //                                   }];
                               }
                               
                               
                           }];
=======
    LogInNavi *logIn = [[LogInNavi alloc] init];
    // 选择模态动画
    [logIn setModalPresentationStyle:UIModalPresentationFullScreen];
    [self presentViewController:logIn animated:YES completion:^{
        
    }];
>>>>>>> 5aabf5f3ed3bf002994c076f8caa1ea0a394d1cf
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)switchAction:(id)sender
{
    UISwitch *switchButton = (UISwitch *)sender;
    BOOL isButton = [switchButton isOn];
    if (isButton) {
        self.view.window.alpha = 1;
    } else {
        self.view.window.alpha = 0.618;
    }
}





@end
